import fg from "fast-glob";
import fs from "fs-extra";
import path from "path";
import { UnityHelper } from "./UnityHelper.js";
import { Record } from "./Record.js";
import { toolchain } from "../toolchain.js";
import { ProjectHelper } from "./ProjectHelper.js";

export class IconStriper {
    private imgRoots = ['icon'];

    public async removeUseless(): Promise<void> {
        const keepMap: { [file: string]: string } = {};
        const usedByCfgMap: { [icon: string]: string } = {};

        // 收集配置中配了的图标
        //#region 
        await ProjectHelper.readKeepCfg(keepMap, usedByCfgMap);
        //#endregion

        // 收集用到的guid
        //#region 
        const usedGUIDMap = await UnityHelper.collectUsedGUID(toolchain.opts.projectRoot);
        //#endregion

        // 收集图片
        //#region 
        let cnt = 0;
        for (const r of this.imgRoots) {
            const imgRoot = path.join('Assets/AssetSources', r);
            const imgs = await fg(['**/*.png', '**/*.jpg', '**/*.tga'], { cwd: path.join(toolchain.opts.projectRoot, imgRoot) });
            for (const img of imgs) {
                const iconID = Number(path.basename(img, path.extname(img)));
                if (iconID >= 210000 || iconID <= 220070) {
                    // 货币图标不删
                    continue;
                }
                const f = path.join(imgRoot, img);
                if (keepMap[f]) {
                    continue;
                }
                if (!usedByCfgMap[(r + '/' + img).toLowerCase()]) {
                    // 未被配置
                    const file = path.join(toolchain.opts.projectRoot, f);
                    const metaFile = file + '.meta';
                    const guid = await UnityHelper.readGUID(metaFile);
                    if (!usedGUIDMap[guid]) {
                        // 未被直接引用
                        await fs.unlink(file);
                        await fs.unlink(metaFile);
                        await Record.Instance.recordGUID(guid, file);
                        cnt++;
                    }
                } else {
                    // console.log('used by code:', img);
                }
            }
        }
        //#endregion

        console.log('deleted images cnt:', cnt);
    }
}
